package org.vehicle.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class CountDeviceProtocolHandle {
	private static Logger logger = LogManager.getLogger(CountDeviceProtocolHandle.class.getName());
	
	public static Long[] protocolHandle(String protocolData){
		protocolData=protocolData.replace(" ", "");
		protocolData=protocolData.substring(2,protocolData.length()-2);
		String hexProtocolData=hexStringToString(protocolData);
		Long[] longArr=new Long[2];
		if("93".equals(hexProtocolData.substring(4,6))){
			Long upData = Long.valueOf(hexProtocolData.substring(8,16),16);
			Long downData = Long.valueOf(hexProtocolData.substring(16,24),16);
			longArr[0]=upData;
			longArr[1]=downData;
			return longArr;
		}else{
			String state = hexProtocolData.substring(8,10);
			if("15".equals(state)){
				logger.error("计数器清零失败");
			}
			longArr[0]=0l;
			longArr[1]=0l;
			return longArr;
		}
		
	}
	
	public static String getClearCommand(){
		String command="";
		command+=strTo16("0001120013");
		command="02"+command+"03";
		return command;
	}
	public static String getCountCommand(){
		String command="";
		command+=strTo16("0001130014");
		command="02"+command+"03";
		return command;
	}
	
	private static String strTo16(String s) {
	    String str = "";
	    for (int i = 0; i < s.length(); i++) {
	        int ch = (int) s.charAt(i);
	        String s4 = Integer.toHexString(ch);
	        str = str + s4;
	    }
	    return str;
	}
	
	private static String hexStringToString(String s) {
	    if (s == null || s.equals("")) {
	        return null;
	    }
	    s = s.replace(" ", "");
	    byte[] baKeyword = new byte[s.length() / 2];
	    for (int i = 0; i < baKeyword.length; i++) {
	        try {
	            baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    try {
	        s = new String(baKeyword, "UTF-8");
	        new String();
	    } catch (Exception e1) {
	        e1.printStackTrace();
	    }
	    return s;
	}
	public static void main(String[] args) {
//		String str="0230303031393331303030303030303030303030303030303030303030303030303030303030303031413503";
//		System.out.println(protocolHandle(str)[1]);
//				
	System.out.println(getClearCommand());
	System.out.println(getCountCommand());
	}
	
}
